package com.itcast.springboot.sessionManager;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**
 * @Author 郭泽鹏
 * @Date 2020/8/18 14:31
 * @Version 1.0
 * @Description 自定义sessionManager
 */
@Slf4j
public class CustomSessionManager extends DefaultWebSessionManager {
    /**
     * 头信息中具有sessionId
     *      请求头 Authorization 中包含sessionId
     * 指定sessionId的获取方式
     */
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        //获取请求头中Authorization的数据
        String id = WebUtils.toHttp(request).getHeader("Authorization");
        if (StringUtils.isEmpty(id)){
            log.warn("id is empty...");
            //如果没有请求头，会生成sessionId
//            return super.getSessionId(request, response);
            //直接返回未登录
            return null;
        }else{
            log.info("--->" + id);
            //返回sessionId
            //header：sessionId从请求头header中获取
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "header");
            //当前的请求头id是什么
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            //当前的sessionId是否要验证
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return id;
        }
    }
}